package com.service.mybatis.service.impl;

import cn.hutool.core.map.MapBuilder;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.model.pojo.Query;
import com.common.model.pojo.DelFlag;
import com.service.mybatis.pojo.BasicEntity;
import com.service.mybatis.pojo.IdEntity;
import com.service.mybatis.pojo.SuperEntity;
import com.service.mybatis.service.ISuperService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * service实现父类
 * 提取一个中间层
 * @author ccf
 */
public class SuperServiceImpl<M extends BaseMapper<T>, T extends IdEntity> extends ServiceImpl<M, T> implements ISuperService<T> {


    @Override
    public boolean isExistName(String id, String name) {
        return isExistField(id, name, NAME);
    }

    @Override
    public boolean isExistField(String id, String fieldValue, String fieldName) {
        if (StrUtil.isEmpty(fieldValue)){
            return false;
        }
        Map<String, Object> map = new HashMap<>();
        map.put(fieldName, fieldValue);
        List<T> ts = baseMapper.selectByMap(map);
        if (ts.size() == 0){
            return false;
        } else if(ts.size() == 1 && StrUtil.isNotBlank(id) ){
            T t = ts.get(0);
            if (id.equals(t.getId())){
                return false;
            } else {
                return true;
            }
        } else {
            return true;
        }
    }


    @Override
    public boolean isExistByMap(String id, String fieldValue, String fieldName, Map<String, Object> map) {
        if (StrUtil.isEmpty(fieldValue)){
            return false;
        }
        map.put(fieldName, fieldValue);
        List<T> ts = baseMapper.selectByMap(map);
        if (ts.size() == 0){
            return false;
        } else if(ts.size() == 1 && StrUtil.isNotBlank(id) ){
            T t = ts.get(0);
            if (id.equals(t.getId())){
                return false;
            } else {
                return true;
            }
        } else {
            return true;
        }
    }
}
